package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class OrderReceiver {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;

    @PostConstruct
    public void orderCancal(){
        //获取阻塞队列
        RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
        //创建单例线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->{
            while(true){
                String orderNo = "";
                try{
                    Object value = blockingDeque.take();
                    if (ObjectUtils.isNotEmpty(value)) {
                        orderNo = value.toString();
                    }
                }catch (Exception e){
                    log.error("延迟队列关单异常，订单编号：{}，异常原因：{}",orderNo,e.getMessage());
                }
                if(StringUtils.isNotEmpty(orderNo)){
                    log.info("关闭订单，订单编号：{}",orderNo);
                    //关闭订单
                    orderInfoService.orderCancel(orderNo);
                }
            }
        });
    }
}
